﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace UlsStudio.Engine.Database
{
    /// <summary>
    /// Used to speed up reading from a IDataReader
    /// </summary>
    internal class DataReaderCache
    {
        private DataReaderCache()
        {
            this.ColIndexCache = new Dictionary<string, int>();
        }
        public DataReaderCache(IDataReader reader)
            : this()
        {
            this.Reader = reader;

            this.FieldNames = new List<string>(this.Reader.FieldCount);
            for (int i = 0; i < this.Reader.FieldCount; i++)
            {
                string existingFieldName = this.Reader.GetName(i);
                this.FieldNames.Add(existingFieldName);
            }
        }

        public int GetOrdinal(string fieldName)
        {
            if (!this.ColIndexCache.ContainsKey(fieldName))
            {
                this.ColIndexCache.Add(fieldName, Reader.GetOrdinal(fieldName));
            }

            return this.ColIndexCache[fieldName];
        }

        public bool ExistsField(string fieldName)
        {
            return this.FieldNames.Contains(fieldName);
        }

        public string GetString(string fieldName)
        {
            int i = GetOrdinal(fieldName);
            if (this.Reader.IsDBNull(i)) return string.Empty;
            else return this.Reader.GetString(i);
        }

        public Guid GetGuid(string fieldName)
        {
            int i = GetOrdinal(fieldName);
            if (this.Reader.IsDBNull(i)) return Guid.Empty;
            else return this.Reader.GetGuid(i);
        }

        public List<string> FieldNames { get; set; }
        public Dictionary<string, int> ColIndexCache { get; set; }
        public IDataReader Reader { get; set; }
    }
}
